package com.xmutca.micro.uaa.config;

import com.xmutca.micro.uaa.security.AuthenticationTokenFilter;
import com.xmutca.micro.uaa.security.JwtTokenFactory;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Created by chunchengpeng on 17/7/27.
 */
@Configuration
@EnableWebSecurity
@Slf4j
@AllArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @NonNull
    private UserDetailsService userDetailsService;

    @NonNull
    private JwtTokenFactory jwtTokenFactory;

    @Bean
    public AuthenticationTokenFilter getAuthenticationTokenFilter() throws Exception {
        return new AuthenticationTokenFilter(jwtTokenFactory, userDetailsService, authenticationManagerBean());
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .disable()
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
            .authorizeRequests()
                .antMatchers("/auth/**").permitAll()
                .antMatchers("/api/**").authenticated()
                .and()
            .addFilterBefore(getAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}
